﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

using umbraco.BusinessLogic;

namespace CreativeMinds.Umbraco.Installation {
	public class DatabaseHelper {
		private List<SQLPackage> packages;
		private string connectString;

		public DatabaseHelper(string connectString, List<SQLPackage> packages) {
			this.connectString = connectString + ";transaction binding=Explicit Unbind;";
			this.packages = packages;
		}

		public void Execute() {
			SQLPackage package = null;
			using (SqlConnection connection = new SqlConnection(this.connectString)) {
				try {
					SqlCommand command = new SqlCommand();
					command.Connection = connection;
					connection.Open();

					foreach (SQLPackage p in this.packages) {
						package = p;

						command.CommandText = p.Script;
						command.ExecuteNonQuery();
					}
				}
				catch (SqlException ex) {
					Log.Add(LogTypes.Error, -1, String.Format("Error in CreativeMinds.Umbraco.Installation.DatabaseInstaller, error: {0}, key {1}", ex.Message, (package != null ? package.Key : "unknown")));
				}
			}
		}
	}
}